package AAAA.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class fz {

    private  fz(){};
    private static SqlSessionFactory sqlSessionFactory;

    /**
     * 类加载时初始化sqlSessionFactory对象
     */
    static {
        try {
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            sqlSessionFactory = sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static ThreadLocal<SqlSession> local = new ThreadLocal<SqlSession>();

    public static SqlSession openSession() {
        SqlSession sqlSession = local.get();
        if(sqlSession != null){
            sqlSession=sqlSessionFactory.openSession();
            //将sqlsession对象绑定到当前线程
            local.set(sqlSession);
        }
        return sqlSession;

    }
    public static void closeSession(SqlSession sqlSession){
        if(sqlSession != null){
            sqlSession.close();
            local.remove();
        }

    }
}